<?php
namespace app\admin\controller;
use think\Controller;
use app\admin\model\Amdin;

class Index extends  Controller
{
    public function index()
    {
        $admin = session('admin');
      
        if (!$admin) {
            
            return $this->fetch('login');
        } 
        return $this->fetch();
    }
	
    /**
     * 后台主页
     * @return [type] [description]
     */
    public function welcome()
    {
        return $this->fetch();
    }

    /**
     * 管理员登录
     * @return [type] [description]
     */
    public function login()
    {
        if (!request()->isPost()) {
            $this->error('请求不合法');
        }
        if(!captcha_check(input('post.verify'))){
            $this->error('验证码不正确');
        }
        $username = input('post.username');
        try {
            // 邮箱登录
            if (strpos($username,'@') !== false) {
                $admin = model('Admin')->getByEmail($username);
            }else{
                $admin = model('Admin')->getByName($username);
            }   
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        if (!$admin || $admin->status != 1) {
            $this->error('账号不存在或者被禁用');
        }

        if (md5(input('post.password')) != $admin->password) {
            $this->error('密码不正确');
        }
        $times = $admin->login_times + 1;
        model('Admin')::where('id',$admin->id)->update(['login_times'=>$times]);
        session('admin',$admin);
        $this->success('登录成功','index/index');
    }

    // 退出登录
    public function logout()
    {
        session(null);
        $this->redirect(url('index/index'));
    }

    // 修改密码
    public function change_pwd()
    {
        return $this->fetch();
    }

    // 修改密码检测
    public function change_check()
    {
        if (!request()->isPost()) {
            $this->error('请求不合法');
        }
        $cur_admin = session('admin');
        if (md5(input('post.old')) != $cur_admin->password) {
            $this->error('原始密码不正确');
        }
        if (input('post.new') != input('post.confirm')) {
            $this->error('确认密码不一致');
        }
        if (input('post.new') == input('post.old')) {
            $this->error('新密码不能和原密码一致');
        }
       model('Admin')::where('id',$cur_admin->id)->update(['password'=>md5(input('post.new'))]);
       session(null);
       $this->success('密码修改成功，请重新登录','index/index');
    }
}
